<template>
    <div class="toolbox-header">
      <h2><el-icon><box /></el-icon> 设计工具箱</h2>
      <div class="search-box">
        <el-input
          v-model="searchText"
          placeholder="搜索组件..."
          clearable
          @clear="handleSearchClear"
        >
          <template #prefix>
            <el-icon><search /></el-icon>
          </template>
        </el-input>
      </div>
      <div class="toolbox-tabs">
        <el-tabs v-model="activeTab" stretch>
          <el-tab-pane name="components">
            <template #label>
              <el-icon><menu /></el-icon> 组件
            </template>
          </el-tab-pane>
          <el-tab-pane name="favorites">
            <template #label>
              <el-icon><star /></el-icon> 收藏
            </template>
          </el-tab-pane>
          <el-tab-pane name="recent">
            <template #label>
              <el-icon><clock /></el-icon> 最近
            </template>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    
    <div class="toolbox-content">
      <!-- 组件库 -->
      <div v-show="activeTab === 'components'" class="components-section">
          <el-collapse v-model="activeCategories" accordion>
            <el-collapse-item 
              v-for="category in categories" 
              :key="category" 
              :title="category" 
              :name="category"
            >
              <div class="component-grid">
                <div 
                  v-for="component in filteredComponents.filter(c => c.category === category)"
                  :key="component.name"
                  class="component-card"
                  draggable="true"
                  @dragstart="handleDragStart($event, component)"
                  @click="handleSelect(component.name)"
                >
                  <div class="component-thumbnail">
                    <el-icon v-if="component.icon" class="component-icon">
                      <component :is="component.icon" />
                    </el-icon>
                    <div v-else class="component-placeholder">
                      {{ component.label.charAt(0) }}
                    </div>
                  </div>
                  <div class="component-info">
                    <div class="component-name">{{ component.label }}</div>
                    <div class="component-actions">
                      <el-button 
                        size="small" 
                        text 
                        @click.stop="toggleFavorite(component.name)"
                      >
                        <el-icon :color="isFavorite(component.name) ? '#ffcc00' : ''">
                          <star-filled />
                        </el-icon>
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
      </div>

      <!-- 收藏组件 -->
      <div v-show="activeTab === 'favorites'" class="favorites-section">
          <div v-if="favoriteComponents.length" class="component-grid">
            <div 
              v-for="comp in favoriteComponents" 
              :key="comp.name"
              class="component-card"
              draggable="true"
              @dragstart="handleDragStart($event, comp)"
              @click="handleSelect(comp.name)"
            >
              <div class="component-thumbnail">
                <el-icon v-if="comp.icon" class="component-icon">
                  <component :is="comp.icon" />
                </el-icon>
                <div v-else class="component-placeholder">
                  {{ comp.label.charAt(0) }}
                </div>
              </div>
              <div class="component-info">
                <div class="component-name">{{ comp.label }}</div>
              </div>
            </div>
          </div>
          <el-empty v-else description="暂无收藏组件" />
      </div>

      <!-- 最近使用组件 -->
      <div v-show="activeTab === 'recent'" class="recent-section">
          <div v-if="recentComponents.length" class="component-grid">
            <div 
              v-for="comp in recentComponents" 
              :key="comp.name"
              class="component-card"
              draggable="true"
              @dragstart="handleDragStart($event, comp)"
              @click="handleSelect(comp.name)"
            >
              <div class="component-thumbnail">
                <el-icon v-if="comp.icon" class="component-icon">
                  <component :is="comp.icon" />
                </el-icon>
                <div v-else class="component-placeholder">
                  {{ comp.label.charAt(0) }}
                </div>
              </div>
              <div class="component-info">
                <div class="component-name">{{ comp.label }}</div>
              </div>
            </div>
          </div>
          <el-empty v-else description="暂无最近使用组件" />
      </div>
    </div>
</template>

<script>
import { defineComponent, ref, computed, onMounted } from 'vue'
import { 
  Search,
  Clock,
  Star,
  StarFilled,
  Box,
  Menu
} from '@element-plus/icons-vue'

export default defineComponent({
  name: 'ComponentList',
  components: {
    Search,
    Clock,
    Star,
    StarFilled,
    Box,
    Menu
  },
  props: {
    components: {
      type: Array,
      required: true
    },
    activeComponent: {
      type: String,
      default: ''
    }
  },
  emits: ['selectComponent'],
  setup(props, { emit }) {
    // 搜索文本
    const searchText = ref('')
    
    // 活动的分类
    const activeCategories = ref(['Basic', 'Form', 'Data', 'Feedback', 'Layout'])    
    // 显示最近使用
    const showRecent = ref(false)
    
    // 显示收藏
    const showFavorites = ref(false)
    
    // 收藏组件
    const favorites = ref([])
    
    // 最近使用组件
    const recentComponents = ref([])
    
    // 初始化本地存储数据
    onMounted(() => {
      const savedFavorites = localStorage.getItem('componentFavorites')
      if (savedFavorites) {
        favorites.value = JSON.parse(savedFavorites)
      }
      
      const savedRecent = localStorage.getItem('componentRecent')
      if (savedRecent) {
        recentComponents.value = JSON.parse(savedRecent)
      }
    })
    
    // 过滤后的组件列表
    const filteredComponents = computed(() => {
      if (!searchText.value) {
        return props.components
      }
      
      const lowerSearchText = searchText.value.toLowerCase()
      return props.components.filter(component => {
        return component.label.toLowerCase().includes(lowerSearchText) ||
               component.name.toLowerCase().includes(lowerSearchText) ||
               (component.description && component.description.toLowerCase().includes(lowerSearchText))
      })
    })
    
    // 获取所有分类
    const categories = computed(() => {
      const categorySet = new Set()
      props.components.forEach(component => {
        if (component.category) {
          categorySet.add(component.category)
        }
      })
      return Array.from(categorySet)
    })
    
    // 收藏组件列表
    const favoriteComponents = computed(() => {
      return props.components.filter(comp => 
        favorites.value.includes(comp.name)
      )
    })
    
    // 检查是否收藏
    const isFavorite = (name) => {
      return favorites.value.includes(name)
    }
    
    // 切换收藏状态
    const toggleFavorite = (name) => {
      const index = favorites.value.indexOf(name)
      if (index === -1) {
        favorites.value.push(name)
      } else {
        favorites.value.splice(index, 1)
      }
      localStorage.setItem('componentFavorites', JSON.stringify(favorites.value))
    }
    
    // 显示组件描述
    const showDescription = (component) => {
      ElMessage({
        message: component.description || '暂无描述',
        grouping: true,
        duration: 3000
      })
    }
    
    // 处理选择组件
    const handleSelect = (index) => {
      // 添加到最近使用
      const comp = props.components.find(c => c.name === index)
      if (comp) {
        const existingIndex = recentComponents.value.findIndex(c => c.name === index)
        if (existingIndex !== -1) {
          recentComponents.value.splice(existingIndex, 1)
        }
        recentComponents.value.unshift(comp)
        if (recentComponents.value.length > 5) {
          recentComponents.value.pop()
        }
        localStorage.setItem('componentRecent', JSON.stringify(recentComponents.value))
      }
      
      emit('selectComponent', index)
    }
    
    // 清除搜索
    const handleSearchClear = () => {
      searchText.value = ''
    }

    // 处理拖拽开始
    const handleDragStart = (event, component) => {
      event.dataTransfer.setData('text/plain', component.name)
      event.dataTransfer.effectAllowed = 'copy'
    }

    // 当前活动标签页
    const activeTab = ref('components')
    
    return {
      searchText,
      activeCategories,
      filteredComponents,
      categories,
      showRecent,
      showFavorites,
      recentComponents,
      favoriteComponents,
      isFavorite,
      toggleFavorite,
      showDescription,
      handleSelect,
      handleSearchClear,
      handleDragStart,
      activeTab
    }
  }
})
</script>

<style scoped>
.designer-toolbox {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: var(--el-bg-color-page);
  border-right: 1px solid var(--el-border-color-light);
}

.toolbox-header {
  padding: 16px;
  border-bottom: 1px solid var(--el-border-color-light);
}

.toolbox-header h2 {
  display: flex;
  align-items: center;
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.toolbox-header h2 .el-icon {
  margin-right: 8px;
}

.search-box {
  margin-bottom: 12px;
}

.toolbox-tabs {
  margin-top: 8px;
}

.toolbox-tabs .el-tabs__item {
  padding: 0 8px;
  height: 32px;
  line-height: 32px;
}

.toolbox-tabs .el-tabs__item .el-icon {
  vertical-align: middle;
  margin-right: 4px;
}

.toolbox-content {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.components-section,
.favorites-section,
.recent-section {
  flex: 1;
  overflow: hidden;
}

.component-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(40px, 1fr));
  gap: 4px;
  padding: 4px;
  width: 100%;
}

.component-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  padding: 2px;
}

.component-item:hover {
  opacity: 0.8;
}

.component-icon {
  font-size: 14px;
}

.component-name {
  font-size: 8px;
  line-height: 1;
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: clip;
  width: 100%;
  margin-top: 0;
  font-weight: normal;
  color: var(--el-text-color-secondary);
}

.component-actions {
  margin-left: 4px;
}

.el-collapse {
  border: none;
}

.el-collapse-item__header {
  padding: 0 16px;
  height: 40px;
  line-height: 40px;
  font-weight: 500;
  background-color: var(--el-bg-color-page);
  border: none;
}

.el-collapse-item__content {
  padding: 0;
}

.el-empty {
  padding: 40px 0;
}

.el-scrollbar {
  height: 100%;
}
</style>